<script setup lang="ts">
import bg from 'src/assets/previous-works/p1.webp'
import PhotoCard from './PhotoCard.vue'
import type { PreviousWork } from '~/api'
import { getPreviousWorks, getSchedules } from '~/api'

const activeKey = ref('')
const router = useRouter()
const workName = ref(useRoute().query?.worksName)

const store = useTeamInfoStore()

const { basicInfo } = storeToRefs(store)

const { data: works, run: getList } = useRequest(getPreviousWorks, {
  manual: true,
})

const { run: getSchedulesApi, data: schedules, loading } = useRequest(getSchedules, {
  manual: true,
  onSuccess(d) {
    activeKey.value = d.data[0]?.key
    if (d.data?.length)
      getList({ scheduleId: activeKey.value, worksName: workName.value })
  },
})

const groupList = computed(() => {
  const arr = []
  if (!works.value)
    return {}
  return works.value.data.reduce<Record<string, PreviousWork[]>>((obj, d) => {
    arr.push(d)
    return arr
  }, {})
})

if (basicInfo.value?.scheduleId)
  getSchedulesApi(`${basicInfo.value.scheduleId}`)

function search() {
  getList({ scheduleId: activeKey.value, worksName: workName.value })
}

function hanldeUpdate(key: string) {
  if (!key)
    return
  activeKey.value = key
  search()
}

function backPtah() {
  router.back()
}
</script>

<template>
  <PageItem :bg="bg" show-footer :content-style="{ flex: 1 }" style="justify-content: start;">
    <div h-full py="4vw">
      <!-- <n-button text type="primary">
        <span i="i-carbon-arrow-left" />
        返回
      </n-button> -->
      <n-button text type="primary" ghost @click="backPtah">
        <span class="i-carbon-arrow-left" m="r-2" />返回
      </n-button>
      <n-scrollbar trigger="none">
        <n-spin :show="loading">
          <n-tabs v-model:value="activeKey" @update-value="hanldeUpdate">
            <n-tab-pane v-for="item of schedules?.data" :key="item.key" :name="item.key" :label="`${item.val}大赛作品`" />
          </n-tabs>
          <div>
            <n-input-group>
              <n-input v-model:value="workName" :style="{ width: '100%', border: '1px solid rgba(186, 54, 210, 1)' }" />
              <n-button type="primary" ghost style="height:36px" @click="search">
                <span class="i-carbon:search" />
              </n-button>
            </n-input-group>
          </div>
        </n-spin>
      </n-scrollbar>
    </div>
    <div>
      <div grid="~ cols-4 justify-center gap-4vw lt-lg:(cols-1)" m="b-10">
        <template v-if="groupList.length">
          <PhotoCard v-for="(item, index) of groupList" :id="item.worksId" :key="index" :max-height="150" :title="item.worksName" :desc="item.content" :img-url="item.worksImgMainUrl" />
        </template>
      </div>
    </div>
  </PageItem>
</template>
